/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.thienloc.omap.controller.report;

import java.util.Comparator;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author GiangLT
 */
public class SyntaxOrdering implements Comparator<String> {

    private final Map<String, Integer> syntaxOrderMap;
    private AtomicInteger index1;
    private AtomicInteger index2;

    public SyntaxOrdering(Map<String, Integer> syntaxOrderMap) {
        this.syntaxOrderMap = syntaxOrderMap;
        index1 = new AtomicInteger(syntaxOrderMap.size() + 1);
        index2 = new AtomicInteger(-1);
    }

    @Override
    public int compare(String o1, String o2) {
        try {
            Integer order1 = syntaxOrderMap.get(o1);
            Integer order2 = syntaxOrderMap.get(o2);
            if (order1 == null) {
                order1 = index1.incrementAndGet();
            }
            if (order2 == null) {
                order2 = index2.decrementAndGet();
            }
            return order1 - order2;
        } catch (Exception ex) {
            Logger.getLogger(SyntaxOrdering.class.getName()).log(Level.SEVERE, null, ex);
            return 0;
        }
    }

}
